import json
import requests
from utils.ini_util import IniFiles
from utils.log_util import logger

api_url = IniFiles.read_ini()['host']['api_url']


class RestClient:
    def __init__(self):
        self.api_url = api_url
        # 创建一个会话，登录认证后，能保存cookie或者session
        self.session = requests.Session()

    # 执行接口，打印返回日志
    def do_request(self, url, method, **kwargs):
        """返回接口相应的JSON格式"""
        response = self.request(url, method, **kwargs)
        if response.status_code:
            logger.info("接口返回信息，状态码>>>{}".format(response.status_code))
        response = response.json()
        logger.info("接口返回信息，JSON格式内容>>>\n{}".format(json.dumps(response, indent=4, ensure_ascii=False)))
        return response

    def request(self, url, method, **kwargs):
        # 请求日志打印
        self.request_log(url, method, **kwargs)
        if method in ["GET", "get", "Get"]:
            return self.session.get(self.api_url + url, **kwargs)
        elif method in ["POST", "post", "Post"]:
            return self.session.post(self.api_url + url, **kwargs)
        elif method in ["PUT", "put", "Put"]:
            return self.session.put(self.api_url + url, **kwargs)
        elif method in ["DELETE", "delete", "Delete"]:
            return self.session.delete(self.api_url + url, **kwargs)
        else:
            logger.error(f'method错误,当前请求方法{method},请参考接口文档中的请求方法')

    def request_log(self, url, method, **kwargs):
        data = dict(**kwargs).get("data")
        json_data = dict(**kwargs).get("json")
        params = dict(**kwargs).get("params")
        files = dict(**kwargs).get("files")
        headers = dict(**kwargs).get("headers")
        logger.info("接口请求信息，url>>>{}".format(self.api_url + url))
        logger.info("接口请求信息，method>>>{}".format(method))
        if headers is not None:
            logger.info("接口请求信息，headers>>>\n{}".format(json.dumps(headers, indent=4, ensure_ascii=False)))
        if data is not None:
            # indent=4 美观，ensure_ascii=False 解决中文乱码
            logger.info("接口请求信息，data>>>\n{}".format(json.dumps(data, indent=4, ensure_ascii=False)))
        if json_data is not None:
            logger.info("接口请求信息，json>>>\n{}".format(json.dumps(json_data, indent=4, ensure_ascii=False)))
        if params is not None:
            logger.info("接口请求信息，params>>>\n{}".format(json.dumps(params, indent=4, ensure_ascii=False)))
        if files is not None:
            # logger.info("接口请求信息，files>>>\n{}".format(json.dumps(files, indent=4, ensure_ascii=False)))
            # files 二进制流不能json.dumps
            logger.info("接口请求信息，files>>>\n{}".format(files))
        # logger.info("接口请求信息，url>>>{}".format(self.api_url + url))
        # logger.info("接口请求信息，method>>>{}".format(method))
        # for param in list(dict(**kwargs).keys()):
        #     if param:
        #         logger.info(
        #             "接口请求信息，headers>>>\n{}".format(json.dumps(dict(**kwargs).get(param), indent=4, ensure_ascii=False)))
        #     else:
        #         logger.info(f'接口请求**kwargs没有入参')


RestClient = RestClient()

if __name__ == '__main__':
    url = '/cgi-bin/gettoken'
    method = 'get'
    params = {
        "corpid": "ww56a5312cbc695bd3",
        "corpsecret": "-YbU-aXDH0Twug2ghuP8KDDIyyFAlhJQWEyyTp5PYp8"
    }
    res = RestClient.do_request(url=url, method=method, params=params)
    print(res)
